import re

from plugins import CheckPlugin
from helper import get_line_from_file
# from config import logger

def parse_authlog(logfile):
    formats = ['datetime', 'hostname', 'program', 'message']
    pat = re.compile(r'(?P<datetime>.+\s+\d+\s\d+:\d+:\d+)'
                      '\s+(?P<hostname>.+?)\s+(?P<program>.+?):\s+(?P<message>.+)')

    repeated_pat = re.compile(r'last\smessage\srepeated\s(?P<times>\d+)\stimes')
    lines = get_line_from_file(logfile)
    last_line = ''
    for line in lines:
        _tmp_lines = []
        if repeated_pat.search(line) and last_line:
            repeated_times = int(repeated_pat.search(line).group('times'))
            _tmp_lines = [last_line for i in range(repeated_times)]
        elif pat.search(line):
            _tmp_lines = [line]
        for _line in _tmp_lines:
            m = pat.search(_line)
            d = dict(zip(formats, [m.group(i) for i in formats]))
            yield d
        last_line = line

logfile = '/home/yxy/tmp/auth.log'
authlog_data = list(parse_authlog(logfile))

class CheckAuthSu(CheckPlugin):
    topic = 'auth_su'

    def check(self):
        self.results = [d for d in authlog_data if d['program']  == 'su']

class CheckAuthSSH(CheckPlugin):
    topic = 'auth_ssh'

    def check(self):
        pat = re.compile(r'sshd(\[\d+\])?')
        self.results = [d for d in authlog_data if d['program'] if pat.search(d['program'])]

